#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QPainter>
#include <QPixmap>
#include <QMessageBox>
#include <QListWidgetItem>
#include <QTime>
#include <QDebug>

mainWidget::mainWidget(QWidget *parent) : QWidget(parent), ui(new Ui::mainWidget) {
    ui->setupUi(this);
    // 初始化UI
    setFixedSize(geometry().size());
    setWindowFlag(Qt::FramelessWindowHint);

    // 初始化各层实例
    dbHelper = DatabaseHelper::getInstance(this);
    netHelper = new NetworkHelper(this);
    playerHelper = new PlayerHelper(this);

    // 初始化数据库表
    if (dbHelper->isOpen()) {
        dbHelper->createTables();
        // 加载历史记录
        QList<SongInfo> historySongs = dbHelper->queryAllHistorySongs();
        for (const auto& song : historySongs) {
            QString itemText = song.songname + "--" + song.singername;
            ui->listWidget_History->addItem(itemText);
        }
    }

    // 信号槽连接
    // 播放器信号
    connect(playerHelper, &PlayerHelper::positionChanged,
            this, &mainWidget::updatePlayerPosition);
    connect(playerHelper, &PlayerHelper::durationChanged,
            this, &mainWidget::updatePlayerDuration);

    // 网络信号
    connect(netHelper, &NetworkHelper::searchFinished,
            this, &mainWidget::handleSearchResult);
    connect(netHelper, &NetworkHelper::musicUrlReady,
            this, &mainWidget::handleMusicUrl);
    connect(netHelper, &NetworkHelper::errorOccurred,
            this, &mainWidget::handleNetworkError);

    // 列表点击事件
    //connect(ui->listWidget_Search, &QListWidget::itemClicked,
            //this, &mainWidget::playSearchMusic);
    connect(ui->listWidget_Search, &QListWidget::itemClicked, this, [=](QListWidgetItem *item) {
            int row = ui->listWidget_Search->row(item); // 获取点击项的行号
            if (row >= 0) {
                ui->listWidget_Search->setCurrentRow(row); // 强制设置当前选中行
                playSearchMusic(); // 调用播放函数
            }
    });
    connect(ui->listWidget_History, &QListWidget::itemClicked,
            this, &mainWidget::playHistoryMusic);

    // 初始化音量
    ui->VopSlider->setValue(100);
    playerHelper->setVolume(100);
    ui->label_Vop->setText("100");
    ui->listWidget_Search->setSelectionMode(QAbstractItemView::SingleSelection); // 允许单选

        ui->listWidget_Search->setSelectionBehavior(QAbstractItemView::SelectItems); // 点击项即选中
        ui->listWidget_Search->setFocusPolicy(Qt::StrongFocus); // 确保能获取焦点
        ui->listWidget_Search->setEnabled(true); // 启用列表



}

mainWidget::~mainWidget() {
    delete ui;
    delete netHelper;
    delete playerHelper;
    // dbHelper是单例，由DatabaseHelper自身管理
}

// 绘制背景
void mainWidget::paintEvent(QPaintEvent *event) {
    Q_UNUSED(event);
    QPainter painter(this);

    // 加载图片并检查是否有效
    QPixmap bgPix(":/new/prefix1/images/images_background2.jpg");
    if (bgPix.isNull()) {
        // 如果图片加载失败，绘制红色背景作为提示
        painter.fillRect(rect(), Qt::red);
        qWarning() << "背景图片加载失败！请检查资源路径";
        return;
    }

    // 绘制背景（拉伸填充）
    painter.drawPixmap(rect(), bgPix);
}
/*void mainWidget::paintEvent(QPaintEvent *event) {
    Q_UNUSED(event);
    QPainter painter(this);
    painter.drawPixmap(0, 0, width(), height(),
                      QPixmap("/new/prefix1/images/images_background1.jpg"));
}*/

// 关闭按钮
void mainWidget::on_pushButton_Close_clicked() {
    close();
}

// 皮肤按钮
void mainWidget::on_pushButton_Skin_clicked() {
    QPixmap bgPix(":/new/prefix1/C:/Users/21958/Pictures/Screenshots/125620.png");
    QMessageBox::information(this, "提示", "皮肤功能待实现");
}

// 关于按钮
void mainWidget::on_pushButton_About_clicked() {

    QMessageBox::about(this, "关于", "廖炜楠的音乐播放器\n版本 1.0");
}

// 搜索按钮
void mainWidget::on_pushButton_Search_clicked() {
    ui->listWidget_Search->clear();
    dbHelper->clearSearchList();

    QString keyword = ui->lineEdit_Search->text();
    if (keyword.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入搜索关键词");
        return;
    }

    netHelper->searchMusic(keyword);
}

// 音量调节
void mainWidget::on_VopSlider_valueChanged(int value) {
    playerHelper->setVolume(value);
    ui->label_Vop->setText(QString::number(value));
}

// 进度条值变化
void mainWidget::on_progressSlider_valueChanged(int value) {
    QTime time(0, value / 60000, qRound((value % 60000) / 1000.0));
    ui->label_Time->setText(time.toString("mm:ss"));

    if (!mousePress) {
        playerHelper->setPosition(value);
    }
}

// 进度条按下
void mainWidget::on_progressSlider_sliderPressed() {
    mousePress = true;
}

// 进度条释放
void mainWidget::on_progressSlider_sliderReleased() {
    mousePress = false;
    playerHelper->setPosition(ui->progressSlider->value());
}

// 上一曲
void mainWidget::on_pushButton_Front_clicked() {
    currentHistoryRow--;
    if (currentHistoryRow < 0) {
        currentHistoryRow = ui->listWidget_History->count() - 1;
    }

    if (currentHistoryRow < 0) {
        QMessageBox::warning(this, "提示", "没有历史记录");
        return;
    }

    SongInfo song = dbHelper->queryHistorySongById(currentHistoryRow + 1);
    if (song.hash.isEmpty()) {
        QMessageBox::warning(this, "错误", "获取歌曲信息失败");
        return;
    }

    netHelper->getMusicUrl(song.album_id, song.hash);
}

// 播放/暂停
void mainWidget::on_pushButton_Playpause_clicked() {
    if (playerHelper->state() == QMediaPlayer::PlayingState) {
        playerHelper->pause();
    } else if (playerHelper->state() == QMediaPlayer::PausedState) {
        playerHelper->play();
    } else {
        QMessageBox::warning(this, "提示", "请先选择歌曲播放");
    }
}

// 下一曲
void mainWidget::on_pushButton_Next_clicked() {
    currentHistoryRow++;
    if (currentHistoryRow >= ui->listWidget_History->count()) {
        currentHistoryRow = 0;
    }

    SongInfo song = dbHelper->queryHistorySongById(currentHistoryRow + 1);
    if (song.hash.isEmpty()) {
        QMessageBox::warning(this, "错误", "获取歌曲信息失败");
        return;
    }

    netHelper->getMusicUrl(song.album_id, song.hash);
}

// 循环播放
void mainWidget::on_pushButton_loopplay_clicked() {
    QMessageBox::information(this, "提示", "循环播放功能待实现");
}

// 处理搜索结果
void mainWidget::handleSearchResult(const QList<SongInfo>& songs) {
    for (const auto& song : songs) {
        dbHelper->insertSearchSong(song);
        QString itemText = song.songname + "--" + song.singername;
        ui->listWidget_Search->addItem(itemText);
    }
}

// 处理音乐地址
void mainWidget::handleMusicUrl(const QString& playUrl, const QString& lyric) {
    if (playUrl.isEmpty()) {
        QMessageBox::warning(this, "错误", "无法获取播放地址");
        return;
    }

    playerHelper->setMedia(QUrl(playUrl));
    playerHelper->play();

    // 显示歌词
    ui->textBrowser_lyric->setFont(QFont("宋体", 10, QFont::Bold));
    ui->textBrowser_lyric->setTextColor(Qt::white);
    ui->textBrowser_lyric->setText(lyric);
}

// 处理网络错误
void mainWidget::handleNetworkError(const QString& errorMsg) {
    QMessageBox::critical(this, "网络错误", errorMsg);
}

// 更新播放进度
void mainWidget::updatePlayerPosition(qint64 position) {
    if (!mousePress) {
        ui->progressSlider->setValue(position);
    }

    QTime time(0, position / 60000, (position % 60000) / 1000);
    ui->label_Time->setText(time.toString("mm:ss"));
}

// 更新播放时长
void mainWidget::updatePlayerDuration(qint64 duration) {
    ui->progressSlider->setRange(0, duration);
}

// 双击播放搜索列表歌曲
void mainWidget::playSearchMusic() {
    //获取双击的歌曲对应索引，就是数据库当中数据表的ID号
    int row = ui->listWidget_Search->currentRow();
    if (row < 0) return;

    SongInfo song = dbHelper->querySearchSongByRow(row);
    if (song.hash.isEmpty()) {
        QMessageBox::warning(this, "错误", "获取歌曲信息失败");
        return;
    }

    // 插入历史记录
    if (dbHelper->insertHistorySong(song)) {
        QString itemText = song.songname + "--" + song.singername;
        ui->listWidget_History->addItem(itemText);
        currentHistoryRow = ui->listWidget_History->count() - 1;
    }

    netHelper->getMusicUrl(song.album_id, song.hash);
}

// 播放历史列表歌曲
void mainWidget::playHistoryMusic() {
    currentHistoryRow = ui->listWidget_History->currentRow();
    if (currentHistoryRow < 0) return;

    SongInfo song = dbHelper->queryHistorySongById(currentHistoryRow + 1);
    if (song.hash.isEmpty()) {
        QMessageBox::warning(this, "错误", "获取歌曲信息失败");
        return;
    }

    netHelper->getMusicUrl(song.album_id, song.hash);
}

// 鼠标事件（窗口拖动）
void mainWidget::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        mousePress = true;
        movePoint = event->globalPos() - pos();
    }
}

void mainWidget::mouseMoveEvent(QMouseEvent *event) {
    if (mousePress) {
        QPoint movePos = event->globalPos();
        move(movePos - movePoint);
    }
}

void mainWidget::mouseReleaseEvent(QMouseEvent *event) {
    Q_UNUSED(event);
    mousePress = false;
}
